package com.flute.icrawler.app.processor.extractor.special;

import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.flute.icrawler.htmlparser.impl.BasicHtmlParser;
import com.flute.icrawler.htmlparser.util.DOMUtil;
import com.flute.icrawler.framework.framework.CrawlUrl;

public class Ku6CommentAlgo implements IExtractorBelongingsAlgo {
	private static Logger logger = Logger.getLogger(Ku6CommentAlgo.class);
	private static String commenturl = "http://comment.ku6.com/podv-";
	private static String xpath = "//DIV[@class='newPage']/DIV[@class='number']/A[not(@class)]/@href";

	@Override
	public String[] extractor(CrawlUrl url) {
		String id = this.getVideoID(url.getUrl());
		String[] maxpage = this.getMaxPageInfo(commenturl + id + ".html");
		int page = Integer.parseInt(maxpage[0]);
		String href = maxpage[1];
		if (page == 1) {
			return new String[] { commenturl + id + ".html" };
		}
		String[] comments = new String[page];
		for (int i = 1; i <= page; i++) {
			comments[i - 1] = "http://comment.ku6.com/" + href.substring(0, href.lastIndexOf('-') + 1) + i + ".html";
		}
		return comments;
	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	private String[] getMaxPageInfo(String url) {
		try {
			Document doc = new BasicHtmlParser().getDocument(url, BasicHtmlParser.HTML_STATIC);
			List<String> urls = DOMUtil.getNodeHtml(doc, xpath);
			if (urls == null || urls.size() == 0) {
				return new String[] { "1", url };
			}
			String href = urls.get(urls.size() - 1);
			String page = href.substring(href.lastIndexOf('-') + 1, href.lastIndexOf('.'));
			return new String[] { page, href };
		} catch (Exception e) {
			logger.error(e);
		}
		return new String[] { "1", url };
	}

	/**
	 * 视频ID
	 * 
	 * @param url
	 * @return
	 */
	private String getVideoID(String url) {
		return url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CrawlUrl url = new CrawlUrl(null, "http://v.ku6.com/special/show_3903777/SL-cezDsoXi3IZw6.html");
		String[] a = new Ku6CommentAlgo().extractor(url);
		for (String s : a) {
			System.out.println(s);
		}

	}
}
